package c.x.jy.service.utils.mqtt;

 

import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import c.x.jy.common.mqtt.ReadConfig;
import c.x.jy.common.utils.HexUtil;
import c.x.jy.common.utils.HttpUtil;
import c.x.jy.service.redis.RedisUtils;
import c.x.jy.service.utils.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
@SuppressWarnings("all")
@Slf4j
public class MQClientUtil {

 final private static Map <Integer, String> locationMap=new HashMap<Integer, String>() {{
     put(0,"09");
	 put(1,"00");
	 put(2,"01");
	 put(3,"02");
	 put(4,"03"); 
	 put(5,"04");
	 put(6,"05");
	 put(7,"06");
	 put(8,"07");
	 put(9,"08");

	 put(10,"09");
	 put(11,"0C");
	 put(12,"0D");
	 put(13,"0E");
	 put(14,"0F");
	 put(15,"10");
	 put(16,"11");
	 put(17,"12");
	 put(18,"13"); 
	 put(19,"14");
	 put(20,"15");
 }};
	 
	 
	
	public final static String  KEY="MSGID";
	private static int sendMsg(String to, Integer code, String from, String  channel, String msg ,String orderNo) {
		CloseableHttpResponse response = null;
		HttpPost httpPost=null;
		CloseableHttpClient httpclient=null;

		int orderid=RedisUtils.redisUtils  .setIncr(KEY,1l).intValue();
		JSONObject jsonMessage = new JSONObject();
	
		jsonMessage.put("orderNo", orderNo);
		jsonMessage.put("code", code);//
		jsonMessage.put("from", from);
		jsonMessage.put("to", to);	

		jsonMessage.put("channel",channel);
		jsonMessage.put("msg",msg);
		jsonMessage.put("time", System.currentTimeMillis());
		jsonMessage.put("msgId", orderid);
		   MqttMessage message = new MqttMessage(jsonMessage.toJSONString().getBytes());
          message.setQos(1);

               try {
				SpringContextUtils.getBean(MqttClient.class).publish(to,message) ;
				return orderid;
			} catch (MqttPersistenceException e) {
				e.printStackTrace();
			} catch (MqttException e) {

				e.printStackTrace();
			}
           	return 0;
	 
		
	}
	/**
	 * 查询设备在线网络状态
	 *
	 * @param
	 * @return
	 
	public static int queryNetStatus(String clientid) {

		return   HttpUtil.sendget( "api/v2/clients"+clientid);;
	}
*/
	
	public static void main(String[] args) {
		//http://www.xuanzhu123.com:18083//api/v4/clients/xuanzhu_4
		
		//System.out.println(queryDeviceStatus("xuanzhu_4"));
	}
	
	/**
	 * 查询设备在线状态
	 *
	 * @param
	 * @return
	 */
	public static boolean queryDeviceStatus(String clientid) {
		log.info("发送查询是否在线id：{}",clientid);
	//	System.out.println(GetConfig.getCompanyCode()+"   /1");
	JSONObject o=	JSON.parseObject (  HttpUtil.sendget( "/api/v4/clients/"+clientid));
	   if(o.getInteger("code")!=null&&o.getInteger("code")==0) {
		   JSONArray l = o.getJSONArray("data");//.getJSONObject(0).getBoolean("connected")?null:null;
		   for (Object obj : l) {
			    System.out.println(obj);
			    JSONObject r=(JSONObject) obj;
			    if(r.getString("clientid").equals(clientid)&&r.getBoolean("connected")) {
			    	return true;
			    }
		}
	   }
	   else return false;
		//System.out.println( JSON.parseObject (  HttpUtil.sendget( "/api/v4/clients/"+clientid)));
	return false;
	 
	}
	
	public static JSONArray delete  (String clientid) {
		log.info("删除设备在线id：{}",clientid);
	//	System.out.println(GetConfig.getCompanyCode()+"   /1");
		
		return JSON.parseObject (  HttpUtil.sendDelete( "api/v4/clients/"+clientid)).getJSONArray("objects");
	}
	
	/**
	 * 查询所有在线设备
	 * @return
	 */
	public static JSONArray queryAllOnLineDevices( ) {
		log.info("发送查询是否在线");
	//	System.out.println(GetConfig.getCompanyCode()+"   /1");
		return JSON.parseObject (  HttpUtil.sendget( "/api/v4/clients")).getJSONArray("objects");
	}
	
	
	/**
	 * 出货多包纸
	 *
	 * @return
	 */
	public static int sendOutGoods(String clientid, String orderNo, Integer count) {
		log.info("正在开门。。。{}", clientid);
		JSONObject obj=new JSONObject();
		obj.put("orderNo", orderNo);
	 
		return sendMsg(clientid, 20, ReadConfig.getMqttServerClient(), null, obj.toJSONString(),orderNo);
	}
	

 

	public static int sendOutGoods(String clientid, String jsonString) {
		// TODO Auto-generated method stub
		return sendMsg(clientid, 20,ReadConfig.getMqttServerClient(), null, jsonString,JSON.parseObject(jsonString).get("orderNo").toString());
	}


	

    /**
     * 开门  回馈  FF:打开 FE:未打开
     * @param deviceImei
     * @param num           柜门号
     * @param channelnumofpcb  单 PCB最大路数
     * @param no   订单 号
     * @return
     */

	public static int openDoor(String deviceImei,int num  ,int channelnumofpcb,
			String no) {
		JSONObject obj=new JSONObject();
		obj.put("orderNo", no);
		String s=	getHexStringByDevice(num,channelnumofpcb);
    	if(s==null )return 0;
		return  sendMsg(deviceImei, 20,ReadConfig.getMqttServerClient(),"0301"+ s, obj.toJSONString(),no);
	}
	
	public static String getHexStringByDevice(int num  ,int channelnumofpcb) {
	 //	System.out.println(num%channelnumofpcb);
	 	String s=	HexUtil.inttoHexString(((num)/(channelnumofpcb+1))) ;
	// 	System.out.println(num-(Integer.valueOf(s)*channelnumofpcb));
		   String v=	locationMap.get( (num-(Integer.valueOf(s)*channelnumofpcb)));

			if(s==null||v==null)return null;
		return s+v;
	}


/**
 * 发送格子查询，是否打开 00开 02关
 * @param deviceImei
 * @param num
 * @param channelnumofpcb
 * @return
 */
	public static int queryCell(String deviceImei, int num  ,int channelnumofpcb) {
	 
	// String v=	locationMap.get(num>=channelnumofpcb?num%channelnumofpcb:num);
 	//String s=	HexUtil.inttoHexString(((num)/(channelnumofpcb+1))) ;
		String s=	getHexStringByDevice(num,channelnumofpcb);
    	if(s==null )return 0;
		return  sendMsg(deviceImei, 23,ReadConfig.getMqttServerClient(),"0303"+ s, null,null);
	}
	
	/**
	 * 查询订单 
	 * @param deviceImei
	 * @param orderNo
	 * @return
	 */
	public static int queryOrderNo(String deviceImei, String orderNo) { 
		
		return sendMsg(deviceImei, 28,ReadConfig.getMqttServerClient(),"03090000" , null,orderNo);
	}
	
 
}
